<template>
  <el-drawer v-model="drawerVisible" title="批量上传资料" size="70%" direction="rtl">
    <div class="batch-upload-container">
      <!-- 上传区域 -->
      <div class="upload-section">
        <el-form ref="formRef" :model="formData" label-width="100px">
          <el-form-item label="资料分类" prop="category">
            <el-select v-model="formData.category" placeholder="请选择分类" style="width: 200px">
              <el-option label="售前资料" value="presale" />
              <el-option label="验收资料" value="acceptance" />
              <el-option label="技术资料" value="technical" />
              <el-option label="其他资料" value="other" />
            </el-select>
          </el-form-item>

          <el-form-item label="批量上传">
            <el-upload
              ref="uploadRef"
              v-model:file-list="fileList"
              :action="uploadUrl"
              :auto-upload="false"
              :data="uploadData"
              :disabled="formLoading"
              :limit="20"
              :on-change="handleFileChange"
              :on-remove="handleFileRemove"
              :on-exceed="handleExceed"
              accept=".doc,.docx,.pdf,.xls,.xlsx,.ppt,.pptx,.jpg,.png,.gif,.mp4,.zip,.rar"
              multiple
              drag
              class="batch-upload-area"
            >
              <Icon icon="ep:upload-filled" size="80" class="upload-icon" />
              <div class="upload-text">
                <p>将文件拖到此处，或 <em>点击批量上传</em></p>
                <p class="upload-tip">支持同时上传多个文件，最多20个</p>
                <p class="upload-tip"
                  >支持 doc/docx/pdf/xls/xlsx/ppt/pptx/jpg/png/gif/mp4/zip/rar 等格式</p
                >
              </div>
            </el-upload>
          </el-form-item>
        </el-form>
      </div>

      <!-- 文件列表 -->
      <div class="file-list-section" v-if="materialList.length > 0">
        <div class="section-header">
          <h3>待上传文件列表 ({{ materialList.length }}个)</h3>
          <div class="batch-actions">
            <el-button @click="selectAllFiles" size="small">
              {{ allSelected ? '取消全选' : '全选' }}
            </el-button>
            <el-button
              @click="removeSelectedFiles"
              type="danger"
              size="small"
              :disabled="selectedFiles.length === 0"
            >
              删除选中 ({{ selectedFiles.length }})
            </el-button>
          </div>
        </div>

        <div class="file-list">
          <div
            v-for="(material, index) in materialList"
            :key="index"
            class="file-item"
            :class="{
              selected: selectedFiles.includes(index),
              uploading: material.uploading,
              success: material.success,
              error: material.error
            }"
          >
            <div class="file-checkbox">
              <el-checkbox
                :model-value="selectedFiles.includes(index)"
                @update:model-value="(checked) => handleFileSelect(index, checked)"
                :disabled="material.uploading || material.success"
              />
            </div>

            <div class="file-info">
              <div class="file-header">
                <Icon :icon="getFileIcon(material.type)" class="file-type-icon" />
                <span class="file-name">{{ material.originalName }}</span>
                <span class="file-size">({{ material.size }})</span>
              </div>

              <div class="file-details">
                <el-row :gutter="16">
                  <el-col :span="8">
                    <el-input
                      v-model="material.name"
                      placeholder="资料名称"
                      size="small"
                      :disabled="material.uploading || material.success"
                    />
                  </el-col>
                  <el-col :span="6">
                    <el-select
                      v-model="material.type"
                      placeholder="类型"
                      size="small"
                      :disabled="material.uploading || material.success"
                    >
                      <el-option label="Word文档" value="word" />
                      <el-option label="PDF文档" value="pdf" />
                      <el-option label="Excel表格" value="excel" />
                      <el-option label="PPT演示" value="ppt" />
                      <el-option label="图片" value="image" />
                      <el-option label="视频" value="video" />
                      <el-option label="压缩包" value="zip" />
                      <el-option label="其他" value="other" />
                    </el-select>
                  </el-col>
                  <el-col :span="6">
                    <el-input
                      v-model="material.version"
                      placeholder="版本号"
                      size="small"
                      :disabled="material.uploading || material.success"
                    />
                  </el-col>
                  <el-col :span="4">
                    <div class="file-status">
                      <el-icon v-if="material.uploading" class="is-loading">
                        <Loading />
                      </el-icon>
                      <el-icon v-else-if="material.success" color="#67c23a">
                        <Check />
                      </el-icon>
                      <el-icon v-else-if="material.error" color="#f56c6c">
                        <Close />
                      </el-icon>
                      <span v-else class="status-text">待上传</span>
                    </div>
                  </el-col>
                </el-row>

                <el-input
                  v-model="material.remark"
                  placeholder="备注信息（可选）"
                  size="small"
                  class="mt-2"
                  :disabled="material.uploading || material.success"
                />
              </div>

              <div v-if="material.error" class="error-message">
                <el-alert :title="material.errorMessage" type="error" :closable="false" />
              </div>
            </div>

            <div class="file-actions">
              <el-button
                v-if="!material.uploading && !material.success"
                @click="removeFile(index)"
                type="danger"
                size="small"
                text
              >
                <Icon icon="ep:delete" />
              </el-button>
            </div>
          </div>
        </div>
      </div>

      <!-- 上传进度 -->
      <div class="progress-section" v-if="showProgress">
        <div class="progress-info">
          <span>上传进度: {{ completedCount }}/{{ totalCount }}</span>
          <span class="progress-detail"> 成功: {{ successCount }} | 失败: {{ errorCount }} </span>
        </div>
        <el-progress :percentage="progressPercentage" :status="progressStatus" :stroke-width="8" />
      </div>
    </div>

    <template #footer>
      <div class="drawer-footer">
        <el-button @click="drawerVisible = false" :disabled="isUploading">取消</el-button>
        <el-button
          type="primary"
          @click="startBatchUpload"
          :loading="isUploading"
          :disabled="materialList.length === 0 || !formData.category"
        >
          {{ isUploading ? '上传中...' : `开始上传 (${materialList.length}个文件)` }}
        </el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script setup lang="ts">
import { ref, reactive, computed, nextTick } from 'vue'
import type { FormInstance } from 'element-plus'
import { Loading, Check, Close } from '@element-plus/icons-vue'
import { useUpload, getUploadUrl } from '@/components/UploadFile/src/useUpload'
import { MaterialApi, type MaterialVO } from '@/api/agent/manage/material'
defineOptions({ name: 'MaterialBatchUpload' })
import * as FileApi from '@/api/infra/file'
const message = useMessage()
const { t } = useI18n()

const drawerVisible = ref(false)
const formLoading = ref(false)
const isUploading = ref(false)
const formRef = ref<FormInstance>()
const uploadRef = ref()
const fileList = ref([])
const materialList = ref<any[]>([])
const selectedFiles = ref<number[]>([])
const productVersion = ref('')

const formData = reactive({
  category: '',
  relatedId: 0,
  relatedType: 'product'
})

const uploadData = ref({ path: '' })
const { uploadUrl, httpRequest } = useUpload()

// 计算属性
const allSelected = computed(() => {
  const selectableFiles = materialList.value
    .map((_, index) => index)
    .filter((index) => !materialList.value[index].uploading && !materialList.value[index].success)
  return (
    selectableFiles.length > 0 &&
    selectableFiles.every((index) => selectedFiles.value.includes(index))
  )
})

const completedCount = computed(() => {
  return materialList.value.filter((item) => item.success || item.error).length
})

const totalCount = computed(() => materialList.value.length)

const successCount = computed(() => {
  return materialList.value.filter((item) => item.success).length
})

const errorCount = computed(() => {
  return materialList.value.filter((item) => item.error).length
})

const progressPercentage = computed(() => {
  if (totalCount.value === 0) return 0
  return Math.round((completedCount.value / totalCount.value) * 100)
})

const progressStatus = computed(() => {
  if (errorCount.value > 0 && completedCount.value === totalCount.value) {
    return 'exception'
  }
  if (completedCount.value === totalCount.value) {
    return 'success'
  }
  return undefined
})

const showProgress = computed(() => {
  return isUploading.value || completedCount.value > 0
})

/** 处理文件选择 */
const handleFileSelect = (index: number, checked: boolean) => {
  if (checked) {
    if (!selectedFiles.value.includes(index)) {
      selectedFiles.value.push(index)
    }
  } else {
    const idx = selectedFiles.value.indexOf(index)
    if (idx > -1) {
      selectedFiles.value.splice(idx, 1)
    }
  }
}

/** 文件类型映射 */
const getFileType = (fileName: string): string => {
  const ext = fileName.split('.').pop()?.toLowerCase()
  const typeMap: Record<string, string> = {
    doc: 'word',
    docx: 'word',
    pdf: 'pdf',
    xls: 'excel',
    xlsx: 'excel',
    ppt: 'ppt',
    pptx: 'ppt',
    jpg: 'image',
    jpeg: 'image',
    png: 'image',
    gif: 'image',
    mp4: 'video',
    avi: 'video',
    mov: 'video',
    zip: 'zip',
    rar: 'zip'
  }
  return typeMap[ext || ''] || 'other'
}

/** 获取文件图标 */
const getFileIcon = (type: string): string => {
  const iconMap: Record<string, string> = {
    word: 'ep:document',
    pdf: 'ep:document',
    excel: 'ep:document',
    ppt: 'ep:document',
    image: 'ep:picture',
    video: 'ep:video-play',
    zip: 'ep:folder-opened',
    other: 'ep:document'
  }
  return iconMap[type] || 'ep:document'
}

/** 提取文件名（去除扩展名） */
const getFileName = (fileName: string): string => {
  return fileName.replace(/\.[^/.]+$/, '')
}

/** 处理文件变化 */
const handleFileChange = (file: any, fileList: any[]) => {
  if (file.raw) {
    const material = {
      originalName: file.name,
      name: getFileName(file.name),
      type: getFileType(file.name),
      version: productVersion.value,
      remark: '',
      size: `${(file.raw.size / 1024 / 1024).toFixed(2)}MB`,
      file: file.raw,
      uploading: false,
      success: false,
      error: false,
      errorMessage: '',
      fileUrl: ''
    }
    materialList.value.push(material)
  }
}

/** 处理文件移除 */
const handleFileRemove = (file: any, fileList: any[]) => {
  const index = materialList.value.findIndex((item) => item.originalName === file.name)
  if (index > -1) {
    materialList.value.splice(index, 1)
    // 更新选中状态
    selectedFiles.value = selectedFiles.value.filter((i) => i < materialList.value.length)
  }
}

/** 文件数量超限 */
const handleExceed = () => {
  message.error('最多只能同时上传20个文件')
}

/** 移除单个文件 */
const removeFile = (index: number) => {
  materialList.value.splice(index, 1)
  selectedFiles.value = selectedFiles.value
    .filter((i) => i !== index)
    .map((i) => (i > index ? i - 1 : i))
}

/** 全选/取消全选 */
const selectAllFiles = () => {
  const selectableFiles = materialList.value
    .map((_, index) => index)
    .filter((index) => !materialList.value[index].uploading && !materialList.value[index].success)

  if (allSelected.value) {
    selectedFiles.value = []
  } else {
    selectedFiles.value = [...selectableFiles]
  }
}

/** 删除选中文件 */
const removeSelectedFiles = () => {
  const sortedIndexes = [...selectedFiles.value].sort((a, b) => b - a)
  sortedIndexes.forEach((index) => {
    materialList.value.splice(index, 1)
  })
  selectedFiles.value = []
}

/** 打开抽屉 */
const open = (category: string, relatedId: number, version: string) => {
  formData.category = category
  formData.relatedId = relatedId
  productVersion.value = version
  resetForm()
  drawerVisible.value = true
}

defineExpose({ open })

/** 开始批量上传 */
const startBatchUpload = async () => {
  if (!formData.category) {
    message.error('请选择资料分类')
    return
  }

  if (materialList.value.length === 0) {
    message.error('请至少上传一个文件')
    return
  }

  isUploading.value = true

  // 重置所有文件状态
  materialList.value.forEach((material) => {
    material.uploading = false
    material.success = false
    material.error = false
    material.errorMessage = ''
  })

  // 逐个上传文件
  for (let i = 0; i < materialList.value.length; i++) {
    const material = materialList.value[i]

    if (material.success) continue // 跳过已成功的文件

    try {
      material.uploading = true
      console.log(`开始上传文件 ${i + 1}/${materialList.value.length}: ${material.originalName}`)

      // 上传文件
      const fileUrl = await uploadSingleFile(material.file, material.originalName)
      console.log(`文件上传成功，URL: ${fileUrl}`)

      // 保存资料信息
      const materialData: MaterialVO = {
        name: material.name,
        type: material.type,
        category: formData.category,
        version: material.version,
        remark: material.remark,
        relatedId: formData.relatedId,
        relatedType: formData.relatedType,
        size: material.size,
        fileUrl: fileUrl
      }

      await MaterialApi.createMaterial(materialData)
      console.log(`资料信息保存成功: ${material.name}`)

      material.uploading = false
      material.success = true
      material.fileUrl = fileUrl
    } catch (error) {
      material.uploading = false
      material.error = true
      material.errorMessage = error instanceof Error ? error.message : '上传失败'
      console.error(`文件 ${material.originalName} 上传失败:`, error)
    }

    // 添加延迟避免请求过于频繁
    if (i < materialList.value.length - 1) {
      await new Promise((resolve) => setTimeout(resolve, 500))
    }
  }

  isUploading.value = false

  // 显示结果
  const successCount = materialList.value.filter((item) => item.success).length
  const errorCount = materialList.value.filter((item) => item.error).length

  if (errorCount === 0) {
    message.success(`批量上传完成！成功上传 ${successCount} 个文件`)
    emit('success')
  } else {
    message.warning(`批量上传完成！成功 ${successCount} 个，失败 ${errorCount} 个`)
    if (successCount > 0) {
      emit('success')
    }
  }
}
/** 上传单个文件 - 直接使用FileApi */
const uploadSingleFile = (file: File, fileName: string): Promise<string> => {
  return new Promise((resolve, reject) => {
    console.log(`准备上传文件: ${fileName}`)
    
    FileApi.updateFile({ file: file })
      .then((res) => {
        console.log('上传成功响应:', res)
        if (res.code === 0) {
          console.log(`文件上传成功，URL: ${res.data}`)
          resolve(res.data)
        } else {
          console.error('业务错误:', res?.msg)
          reject(new Error(res?.msg || '上传失败'))
        }
      })
      .catch((error) => {
        console.error('上传失败:', error)
        reject(new Error(error?.message || '文件上传失败'))
      })
  })
}

// /** 上传单个文件 - 动态获取上传URL */
// const uploadSingleFile = (file: File, fileName: string): Promise<string> => {
//   return new Promise((resolve, reject) => {
//     console.log(`准备上传文件: ${fileName}`)

//     const uploadOptions = {
//       file: file,
//       filename: fileName,
//       data: { path: `materials/${formData.category}/${fileName}` },
//       onSuccess: (response: any) => {
//         console.log('上传成功响应:', response)
//         if (response && response.code === 0) {
//           console.log(`文件上传成功，URL: ${response.data}`)
//           resolve(response.data)
//         } else {
//           console.error('业务错误:', response?.msg)
//           reject(new Error(response?.msg || '上传失败'))
//         }
//       },
//       onError: (error: any) => {
//         console.error('上传失败:', error)
//         reject(new Error(error.message || '文件上传失败'))
//       }
//     }

//     try {
//       console.log('使用系统httpRequest方法')
//       httpRequest(uploadOptions)
//     } catch (error) {
//       console.error('httpRequest调用失败:', error)
//       reject(error)
//     }
//   })
// }

/** 重置表单 */
const resetForm = () => {
  materialList.value = []
  selectedFiles.value = []
  fileList.value = []
  isUploading.value = false
  uploadRef.value?.clearFiles()
}

const emit = defineEmits(['success'])
</script>

<style lang="scss" scoped>
.batch-upload-container {
  height: 100%;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.upload-section {
  .batch-upload-area {
    width: 100%;

    :deep(.el-upload) {
      width: 100%;
    }

    :deep(.el-upload-dragger) {
      width: 100%;
      height: 160px;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
    }
  }

  .upload-icon {
    color: #409eff;
    margin-bottom: 16px;
  }

  .upload-text {
    text-align: center;

    p {
      margin: 4px 0;
      color: #606266;

      &.upload-tip {
        font-size: 12px;
        color: #909399;
      }

      em {
        color: #409eff;
        font-style: normal;
      }
    }
  }
}

.file-list-section {
  flex: 1;
  overflow: hidden;
  display: flex;
  flex-direction: column;

  .section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;

    h3 {
      margin: 0;
      color: #303133;
    }

    .batch-actions {
      display: flex;
      gap: 8px;
    }
  }

  .file-list {
    flex: 1;
    overflow-y: auto;
    border: 1px solid #e4e7ed;
    border-radius: 6px;

    .file-item {
      display: flex;
      align-items: flex-start;
      padding: 16px;
      border-bottom: 1px solid #f0f0f0;
      transition: all 0.3s;

      &:last-child {
        border-bottom: none;
      }

      &.selected {
        background-color: #f0f9ff;
      }

      &.uploading {
        background-color: #fdf6ec;
      }

      &.success {
        background-color: #f0f9f0;
      }

      &.error {
        background-color: #fef0f0;
      }

      .file-checkbox {
        margin-right: 12px;
        margin-top: 4px;
      }

      .file-info {
        flex: 1;

        .file-header {
          display: flex;
          align-items: center;
          gap: 8px;
          margin-bottom: 12px;

          .file-type-icon {
            font-size: 20px;
            color: #409eff;
          }

          .file-name {
            font-weight: 500;
            color: #303133;
          }

          .file-size {
            color: #909399;
            font-size: 12px;
          }
        }

        .file-details {
          .file-status {
            display: flex;
            align-items: center;
            justify-content: center;
            height: 32px;

            .status-text {
              color: #909399;
              font-size: 12px;
            }
          }
        }

        .error-message {
          margin-top: 8px;
        }
      }

      .file-actions {
        margin-left: 12px;
        margin-top: 4px;
      }
    }
  }
}

.progress-section {
  padding: 16px;
  background: #f8f9fa;
  border-radius: 6px;

  .progress-info {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 8px;
    font-size: 14px;

    .progress-detail {
      color: #909399;
      font-size: 12px;
    }
  }
}

.drawer-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 16px;
  border-top: 1px solid #e4e7ed;
}

.mt-2 {
  margin-top: 8px;
}
</style>
